package com.cn.qtms.service;//类注释设置模板

import com.cn.qtms.common.result.ErrorCode;
import com.cn.qtms.entity.vo.sys.User;
import com.cn.qtms.exception.AppException;
import com.cn.qtms.feign.SysService;
import com.cn.qtms.model.JwtUser;
import com.cn.qtms.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Name:JpaSmsCodeService  短信验证码登陆验证逻辑
 * @Description:
 * @Author: zhangyang
 * @Date: 2019-12-02 15:28
 **/
@Service
@Transactional(readOnly = true)
public class JpaSmsCodeServiceImpl {

    @Autowired
    private RedisTemplate redisTemplate=new RedisTemplate();
    @Autowired
    private SysService sysService;

    public UserDetails loadUserBySmsCode(String phone,String smsCode) throws UsernameNotFoundException {
        // 从库里查用户
        User user = sysService.findByPhone(phone);
        if(user == null) {
            throw new UsernameNotFoundException("phone [" + phone + "] user not found.");
        }
        final JwtUser jwtUser = new JwtUser(user, user.getRoles());
        //获取缓存中的验证码
        String smsCodeCached = (String) redisTemplate.opsForValue().get("verifyCode"+phone);
        if (StringUtil.isEmpty(smsCodeCached)) {
            //从redis中获取的验证码为空,代表没有先获取验证码
            throw new AppException(ErrorCode.SMS_NOT_FOUND.getMessage());
        }
        if (!smsCodeCached.equals(smsCode)) {
            //如果输入的验证码不正确,那么也直接返回该方法
            throw new AppException("验证码输入有误");
        }
        final List<String> roles = user.getRoles();
        //判断角色可用性
        if(roles==null || roles.size()==0){
            throw new AppException(ErrorCode.ACCESS_DENIED.getMessage());
        }
        return new JwtUser(user,roles);
    }
}
